<template>
	<view class="content">
		<image class="img" :style="{ width: width + 'px', height: height + 'px' }" :src="bgImg" mode="" @load="imageLoad"></image>
		<canvas
			:style="{ width: width + 'px', height: height + 'px' }"
			type="2d"
			:ref="canvasId"
			class="canvasbox"
			:canvas-id="canvasId"
			:id="canvasId"
			:disable-scroll="true"
			@touchstart="touchstart"
			@touchmove="touchmove"
			@touchend="touchend"
		>
			<view
				v-for="(item, index) in textList"
				:key="index"
				class="textbox"
				:style="{ top: item.y + 'px', left: item.x + 'px', transform: 'rotate(' + item.angle + 'deg) scale(' + item.scale + ')' }"
				:data-index="index"
				@touchstart.stop="touchstartText($event, index)"
				@touchmove.stop="touchmoveText($event, index)"
				@touchend.stop="touchendText($event, index)"
			>
				<text :style="{ color: item.color, fontSize: 16 + 'px', fontfamily: 'Arial' }">{{ item.text }}</text>
				<uni-icons class="closeicon" type="clear" size="30" @click="deleteText(index)"></uni-icons>
			</view>
		</canvas>

		<image class="img1" :style="{ width: width + 'px', height: height + 'px' }" :src="bgImg1" mode=""></image>

		<canvas class="img1" :canvas-id="canvasId + '1'" :style="{ width: width + 'px', height: height + 'px' }" :id="canvasId + '1'"></canvas>

		<view class="btns" v-if="btnStatus">
			<view class="btns_l">
				<image src="../static/icon/icon4.png" mode="heightFix" @click="changeColor"></image>
				<image src="../static/icon/icon5.png" mode="heightFix" @click="penModeSwitch"></image>
				<image src="../static/icon/icon6.png" mode="heightFix" @click="eraserModeSwitch"></image>
			</view>
			<view class="btns_r">
				<view @click="changeBtns(true)">保存</view>
				<view @click="changeBtns(false)">取消</view>
			</view>
		</view>

		<uni-popup ref="popup1" type="bottom" border-radius="10px 10px 0 0" :is-mask-click="false">
			<view class="popbox">
				<uni-icons class="btn" type="closeempty" size="30" color="#102D40" @click="changInterval(false)"></uni-icons>
				<view class="pop_title">添加的文字</view>
				<view class="pop_1">
					<view :class="{ active: textColor === item }" v-for="(item, index) in textColors" :key="index" :style="{ backgroundColor: item }" @click="selectTextColor(item)"></view>
				</view>
				<view class="pop_input">
					<input type="text" placeholder="请输入" v-model="canvasText" />
				</view>
				<view class="btn1" @click="changInterval(true)">保存</view>
			</view>
		</uni-popup>

		<uni-popup ref="popup" type="bottom" border-radius="10px 10px 0 0" :is-mask-click="false">
			<view class="color_box">
				<view class="color_title">选择画笔颜色</view>
				<view class="color_content">
					<view
						class="color_item"
						:class="{ active: color === item }"
						v-for="(item, index) in colors"
						:key="index"
						:style="{ backgroundColor: item }"
						@click="selectColor(item)"
					></view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
import { pathToBase64, base64ToPath } from 'image-tools';
export default {
	name: 'canvasBox',
	props: {
		canvasId: {
			type: String,
			default: 'canvasId',
			required: true
		},
		bgImg: {
			type: String,
			default: '',
			required: true
		},
		btnStatus: {
			type: Boolean,
			default: false
		}
	},
	watch: {},
	data() {
		return {
			ctx: null,
			ctx1: null,
			width: 0,
			height: 0,
			deviceWidth: 0, //屏幕宽度
			textList: [
				// {
				// 	x: 0,
				// 	y: 0,
				// 	text: '123123123',
				// 	angle: 0,
				// 	scale: 1,
				// 	color: '#000000'
				// }
			],

			textStartX: 0,
			textStartY: 0,

			startX: 0, // 触摸起始点x坐标
			startY: 0, // 触摸起始点y坐标
			startDistance: 0, // 触摸起始两指距离
			startAngle: 0, // 初始旋转角度
			scale: 1, // 缩放比例
			rotation: 0, // 旋转角度

			canvasText: '', //输入框内容

			// 画笔坐标
			penstartX: 0,
			penstartY: 0,

			// 画笔颜色弹框状态
			color: '#000000',
			colors: ['#000000', '#F5222D', '#FA8C16', '#FADB14', '#8BBB11', '#52C41A', '#13A8A8', '#1677FF', '#2F54EB', '#722ED1', '#EB2F96'],
			textColor: '#000000',
			// 白、黑、红、黄、绿、蓝
			textColors: ['#FFFFFF', '#000000', '#FF0000', '#FFFF00', '#00FF00', '#0000FF'],
			eraserMode: false,

			bgImg1: ''
		};
	},
	methods: {
		// 画板保存、取消
		changeBtns(status) {
			if (status) {
				console.log('保存');
				if (this.textList.length > 0) {
					for (let i = 0; i < this.textList.length; i++) {
						const item = this.textList[i];
						this.ctx.save();
						this.ctx.translate(item.x , item.y );
						this.ctx.rotate((item.angle * Math.PI) / 180);
						this.ctx.scale(item.scale, item.scale);

						this.ctx.font = '16px sans-serif';
						this.ctx.fillStyle = item.color;
						this.ctx.fillText(item.text, uni.upx2px(20), uni.upx2px(50));
						this.ctx.restore();
					}
					this.ctx.draw(true);
					this.textList = [];
				}

				console.log('画板数据', this.ctx);

				uni.canvasToTempFilePath({
					canvasId: this.canvasId,
					quality: 0.2,
					success: (res) => {
						console.log(res.tempFilePath);
						pathToBase64(res.tempFilePath).then((res1) => {
							// console.log(res1, '转换的base64图片');
							this.endImage(res1);
						});
					}
				});
			} else {
				console.log('取消', this.$refs);
				// 清空画布
				this.ctx.clearRect(0, 0, this.width, this.height);
				this.ctx.draw(true);
				this.$emit('change', '');
			}
		},

		// 添加移动的文字
		changInterval(type) {
			if (type) {
				if (!this.canvasText) {
					uni.showToast({
						icon: 'none',
						title: '请输入文字'
					});
					return;
				}
				this.textList.push({
					x: 0,
					y: 0,
					text: this.canvasText,
					angle: 0,
					scale: 1,
					color: this.textColor
				});
			}
			this.$refs.popup1.close();
		},

		// 切换画笔颜色
		changeColor() {
			this.eraserMode = false;
			this.$refs.popup.open();
		},

		// 选择画笔颜色
		selectColor(color) {
			this.color = color;
			this.$refs.popup.close();
		},

		// 文字模式
		penModeSwitch() {
			this.eraserMode = false;
			this.$refs.popup1.open();
		},

		// 文字颜色
		selectTextColor(color) {
			this.textColor = color;
		},

		// 橡皮擦模式切换
		eraserModeSwitch() {
			this.eraserMode = true;
		},

		// 最终图片合成
		endImage(img) {
			// 先在ctx1上绘制bgImg,在绘制img
			this.ctx1.drawImage(this.bgImg, 0, 0, this.width, this.height);
			this.ctx1.draw(true);
			this.ctx1.drawImage(img, 0, 0, this.width, this.height);
			this.ctx1.draw(true, () => {
				uni.canvasToTempFilePath({
					canvasId: this.canvasId + '1',
					quality: 0.2,
					success: (res2) => {
						pathToBase64(res2.tempFilePath).then((res11) => {
							console.log(res11, '最终的转换的base64图片');
							this.bgImg1 = res11;
							this.$emit('change', res11);
						});
					}
				});
			});
		},

		// 图片加载
		imageLoad(e) {
			console.log(e, '加载的图片');
			let imageWidth = e.target.width;
			let imageHeight = e.target.height;
			let scale = this.deviceWidth / imageWidth;
			this.width = imageWidth * scale;
			this.height = imageHeight * scale;
			console.log(this.width, this.height, '图片的尺寸');

			this.$nextTick(() => {
				this.ctx = uni.createCanvasContext(this.canvasId);
				this.ctx1 = uni.createCanvasContext(this.canvasId + '1');
				this.ctx1.drawImage(this.bgImg, 0, 0, this.width, this.height);
				this.ctx1.draw();
			});
		},

		// 手指触摸动作开始
		touchstart(e) {
			this.penstartX = e.touches[0].x; // 记录开始触摸的X坐标
			this.penstartY = e.touches[0].y; // 记录开始触摸的Y坐标
			console.log(e.touches[0], '触摸开始');
		},

		// 手指触摸后移动
		touchmove(e) {
			const moveX = e.touches[0].x; // 获取移动中的X坐标
			const moveY = e.touches[0].y; // 获取移动中的Y坐标
			if (this.eraserMode) {
				this.ctx.save(); // 保存当前画布状态
				this.ctx.globalCompositeOperation = 'destination-out'; // 设置全局合成操作
				this.ctx.beginPath(); // 开始路径
				this.ctx.arc(moveX, moveY, 20, 0, 2 * Math.PI); // 增大圆形的半径
				this.ctx.fillStyle = 'rgba(0,0,0,0.5)'; // 设置圆形的填充颜色和透明度
				this.ctx.fill(); // 填充圆形
				this.ctx.moveTo(this.penstartX, this.penstartY); // 移动到指定坐标
				this.ctx.lineTo(moveX, moveY); // 连接到指定坐标
				this.ctx.setLineWidth(20); // 设置线条宽度
				this.ctx.stroke(); // 绘制路径
				this.ctx.restore(); // 恢复画布状态
			} else {
				// 根据起始点和当前点坐标绘制路径
				this.ctx.moveTo(this.penstartX, this.penstartY);
				this.ctx.lineTo(moveX, moveY);
				this.ctx.setLineWidth(1); // 设置线条宽度
				this.ctx.setStrokeStyle(this.color); // 设置线条颜色
				this.ctx.stroke(); // 绘制路径
			}
			this.ctx.draw(true); // 将路径绘制到Canvas上
			this.penstartX = moveX; // 更新起始X坐标
			this.penstartY = moveY; // 更新起始Y坐标
		},

		// 手指触摸动作结束
		touchend() {
			if (!this.butStatus) return;
		},

		// 实现文字点击拖拽开始
		touchstartText(event, index) {
			if (event.touches.length === 1) {
				let text = this.textList[index];
				this.textStartX = event.touches[0].clientX - text.x;
				this.textStartY = event.touches[0].clientY - text.y;
			}

			if (event.touches.length === 2) {
				// 记录两指起始位置和距离
				this.startX = event.touches[0].clientX;
				this.startY = event.touches[0].clientY;
				this.startDistance = this.getDistance(event.touches[0], event.touches[1]);
				this.startAngle = this.getAngle(event.touches[0], event.touches[1]);
			}
		},

		// 实现文字点击拖拽移动
		touchmoveText(event, index) {
			if (event.touches.length === 1) {
				let text = this.textList[index];
				text.x = event.touches[0].clientX - this.textStartX;
				text.y = event.touches[0].clientY - this.textStartY;
			}

			if (event.touches.length === 2) {
				console.log('双指移动距离', event.touches);
				// 计算旋转角度和缩放比例
				const currentX = event.touches[0].clientX;
				const currentY = event.touches[0].clientY;
				const currentDistance = this.getDistance(event.touches[0], event.touches[1]);
				const currentAngle = this.getAngle(event.touches[0], event.touches[1]);

				this.rotation += currentAngle - this.startAngle;
				this.scale = currentDistance / this.startDistance;
				console.log(this.scale, currentDistance, this.startDistance, '旋转角度和缩放比例');
				// 更新旋转和缩放
				this.textList[index].angle = this.rotation;
				this.textList[index].scale = this.scale;

				// 重置起始状态
				this.startX = currentX;
				this.startY = currentY;
				this.startAngle = currentAngle;
			}
		},

		// 在手指离开屏幕时进行一些清理操作
		touchendText(event, index) {
			if (event.touches.length === 2) {
				const currentDistance = this.getDistance(event.touches[0], event.touches[1]);
				this.startDistance = currentDistance;
			}
		},

		// 实现文字点击删除
		deleteText(index) {
			this.textList.splice(index, 1);
		},

		getDistance(p1, p2) {
			return Math.sqrt(Math.pow(p2.clientX - p1.clientX, 2) + Math.pow(p2.clientY - p1.clientY, 2));
		},
		getAngle(p1, p2) {
			const x = p2.clientX - p1.clientX;
			const y = p2.clientY - p1.clientY;
			return Math.atan2(y, x) * (180 / Math.PI);
		}
	},
	mounted() {
		this.deviceWidth = uni.getSystemInfoSync().windowWidth - 22;
		console.log(this.deviceWidth, '屏幕宽度');
	}
};
</script>

<style lang="scss" scoped>
.content {
	width: 100%;
	height: 100%;
	overflow: auto;
	position: relative;
	background-color: transparent;

	.img1 {
		position: absolute;
		top: 0;
		right: 0;
		z-index: 1;
	}

	.img {
		// display: none;
		position: absolute;
		top: 0;
		right: 0;
		z-index: 2;
	}

	.canvasbox {
		position: relative;
		top: 0;
		left: 0;
		right: 0;
		z-index: 3;
		// background-color: red;

		.textbox {
			// background-color: red;
			position: absolute;
			z-index: 999;
			border: 1rpx solid #000000;
			border-radius: 20rpx;
			padding: 20rpx;

			.closeicon {
				position: absolute;
				top: -20rpx;
				left: -20rpx;
			}

			.rotateicon {
				position: absolute;
				bottom: -20rpx;
				right: -20rpx;
			}
		}
	}

	.btns {
		width: 100%;
		display: flex;
		align-items: center;
		justify-content: space-between;
		position: fixed;
		left: 0;
		bottom: 0;
		z-index: 5;
		padding: 0 22rpx;

		.btns_l,
		.btns_r {
			display: flex;
			align-items: center;
		}

		.btns_l {
			image {
				height: 60rpx;
				margin-right: 50rpx;
			}
		}

		.btns_r {
			view {
				width: 144rpx;
				height: 60rpx;
				border-radius: 12rpx 12rpx 12rpx 12rpx;
				font-family: Source Han Sans, Source Han Sans;
				font-weight: 500;
				font-size: 32rpx;
				color: #ffffff;
				line-height: 60rpx;
				text-align: center;
			}

			view:nth-child(1) {
				background: #17b76d;
			}

			view:nth-child(2) {
				background: #2b2b2b;
				margin-left: 20rpx;
			}
		}

		.btn1 {
			width: 224rpx;
			height: 60rpx;
			background: #17b76d;
			border-radius: 12rpx 12rpx 12rpx 12rpx;
			font-family: Source Han Sans, Source Han Sans;
			font-weight: 500;
			font-size: 36rpx;
			color: #ffffff;
			line-height: 60rpx;
			text-align: center;
		}
	}

	.color_box {
		width: 100%;
		height: 300rpx;
		background-color: #ffffff;
		border-radius: 10px 10px 0 0;
		overflow: auto;

		.color_title {
			height: 80rpx;
			line-height: 80rpx;
			font-size: 36rpx;
			color: #333333;
			text-align: center;
			margin-top: 40rpx;
		}

		.color_content {
			width: 100%;
			display: flex;
			flex-wrap: wrap;
			align-items: center;
			margin-top: 20rpx;

			.color_item {
				width: calc(100% / 6);
				height: 50rpx;
				margin-top: 20rpx;
				border-radius: 10rpx;
				cursor: pointer;
			}

			.active {
				border: 1px solid #ffffff;
			}
		}
	}

	.popbox {
		width: 100%;
		height: 478rpx;
		background: #ffffff;
		border-radius: 40rpx 40rpx 0rpx 0rpx;
		padding: 0 74rpx;
		position: relative;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: space-around;

		.btn {
			position: absolute;
			top: 30rpx;
			right: 40rpx;
		}

		.pop_title {
			font-family: Source Han Sans, Source Han Sans;
			font-weight: 500;
			font-size: 36rpx;
			color: #000000;
			line-height: 52rpx;
			text-align: center;
		}
		.pop_1 {
			width: 100%;
			display: flex;
			align-items: center;
			justify-content: space-between;

			view {
				width: 50rpx;
				height: 50rpx;
				border-radius: 50%;
				overflow-x: auto;
				border: 1rpx solid #c4c4c4;
			}

			.active {
				box-shadow: 0 0 10rpx #c4c4c4;
			}
		}
		.pop_input {
			width: 100%;
			height: 92rpx;
			background: #ffffff;
			border-radius: 16rpx 16rpx 16rpx 16rpx;
			border: 1rpx solid #c4c4c4;
			padding: 0 30rpx;

			input {
				width: 100%;
				height: 90rpx;
			}
		}

		.btn1 {
			width: 100%;
			height: 92rpx;
			background: #17b76d;
			border-radius: 16rpx 16rpx 16rpx 16rpx;
			font-family: Source Han Sans, Source Han Sans;
			font-weight: 500;
			font-size: 32rpx;
			color: #ffffff;
			line-height: 92rpx;
			text-align: center;
		}
	}
}
</style>
